module amdar_mongo_mod

  use iso_c_binding
  use mongof_common_mod
  use datetime
  use string
  use container
  use flogger
  use params_mod
  use data_translators_utils_mod
  use amdar_mod

  implicit none

  private

  public amdar_mongo_write

  interface
    integer function amdar_mongoc_insert_platform(cid, name) result(res) bind(c, name='amdar_mongoc_insert_platform')
      use iso_c_binding
      integer(c_int), intent(in) :: cid
      character(c_char), intent(in) :: name
    end function amdar_mongoc_insert_platform

    integer function amdar_mongoc_insert_record(cid, name, timestamp, lon, lat, z, ta, p, rh, ua, va) result(res) bind(c, name='amdar_mongoc_insert_record')
      use iso_c_binding
      integer(c_int), intent(in) :: cid
      character(c_char), intent(in) :: name
      real(c_double), intent(in) :: timestamp
      real(c_float), intent(in) :: lon
      real(c_float), intent(in) :: lat
      real(c_float), intent(in) :: z
      real(c_float), intent(in) :: ta
      real(c_float), intent(in) :: p
      real(c_float), intent(in) :: rh
      real(c_float), intent(in) :: ua
      real(c_float), intent(in) :: va
    end function amdar_mongoc_insert_record
  end interface

contains

  subroutine amdar_mongo_write(mongo_uri, mongo_db, mongo_col, flights, records)

    character(*), intent(in) :: mongo_uri
    character(*), intent(in) :: mongo_db
    character(*), intent(in) :: mongo_col
    type(hash_table_type), intent(in) :: flights
    type(linked_list_type), intent(in) :: records

    integer(c_int) cid_flight, cid_record
    character(12) sid
    type(linked_list_iterator_type) it

    call mongoc_init()

    call handle_mongo_error(mongoc_connect('mongodb://' // trim(mongo_uri), trim(mongo_db), &
      trim(mongo_col) // '_flights' // char(0), cid_flight), __FILE__, __LINE__)

    call handle_mongo_error(mongoc_connect('mongodb://' // trim(mongo_uri), trim(mongo_db), &
      trim(mongo_col) // '_records' // char(0), cid_record), __FILE__, __LINE__)

    call handle_mongo_error(mongoc_create_platform_index(cid_flight), __FILE__, __LINE__)
    call handle_mongo_error(mongoc_create_drift_record_index(cid_record), __FILE__, __LINE__)

    it = linked_list_iterator(records)
    do while (.not. it%ended())
      select type (record => it%value)
      type is (amdar_record_type)
        sid = trim(record%flight%name) // char(0)
        call handle_mongo_error(amdar_mongoc_insert_platform(cid_flight, sid), __FILE__, __LINE__)
        call handle_mongo_error(amdar_mongoc_insert_record(cid_record, sid, &
          record%time%timestamp(), record%lon, record%lat, record%h, record%ta, &
          record%p, record%sh, record%ua, record%va), __FILE__, __LINE__)
      end select
      call it%next()
    end do

    call mongoc_final()

  end subroutine amdar_mongo_write

end module amdar_mongo_mod
